package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.ACT;
import Models.ACB;

public class ACTPresenter extends AbstractPresenter<ACT> {
	final String SINGLEITEM = "act";
	final String MULTIITEM = "acts";
	
	public ArrayList<ACT> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public ACT tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public ACT createItemFromJSONObject(JSONObject jsonObject){
		ACT item = new ACT();
		try{
			item.setActID(jsonObject.getInt("ACTID"));
			
			CustomerPresenter custPresenter = new CustomerPresenter();
			JSONObject jsonFGI = jsonObject.getJSONObject("ACTCustomer");
			item.setActCust(custPresenter.createItemFromJSONObject(jsonFGI));
			
			//Set LabType Collection
			ArrayList<ACB> beers = new ArrayList<ACB>();
			if(!jsonObject.isNull("ACBCollection")){
				Object itm = jsonObject.get("ACBCollection");
				ACBPresenter presenter = new ACBPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						beers.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					beers.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setAcbs(beers);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(ACT item){
		try{
			JSONObject json = new JSONObject();
			json.put("ACTID", item.getActID());
			
			CustomerPresenter custPresenter = new CustomerPresenter();
			json.put("ACTCustomer", custPresenter.createJSON(item.getActCust()));
			
			//Create Beers Collection
			if(item.getAcbs()!=null){
				ACBPresenter presenter = new ACBPresenter();
				if(item.getAcbs().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getAcbs().size(); i++){
						jsonArray.put(presenter.createJSON(item.getAcbs().get(i)));
					}
					json.put("ACBCollection", jsonArray);
				}
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public ACT getEmptyEntity(){
		ACT entity = new ACT();
		return entity;
	}
}
